# 价格策略视图文件
from django.http import JsonResponse
from django.shortcuts import render,HttpResponse,redirect
from django.urls import reverse
from utils.bootstrap import BootStrapForm
from utils.encrypt import md5
from utils.link import filter_reverse
from utils.reponse import BaseResponse
from web import models
from django import forms
from django.core.exceptions import ValidationError, BadRequest
import re
from django.db.models import Q
from utils.pager import Pagination


# 显示价格策略界面
def policy_list(request):
    #获取价格策略 并且排序
    queryset = models.PricePolicy.objects.all().order_by("count")
    pager = Pagination(request=request, query_set=queryset)  # 实例化页码类
    # pager_string = obj.html()  # 生成html代码的页码函数
    # obj.queryset()  # 切片显示前5个数据
    return render(request,"policy_list.html",{"pager":pager})

#显示价格策略添加的form
class PolicyModelForm(BootStrapForm,forms.ModelForm):
    class Meta:
        model = models.PricePolicy  # models.表名
        fields = "__all__"

# 显示价格策略添加功能
def policy_add(request):
    if request.method == "GET":
        form = PolicyModelForm()
        return render(request, "form2.html", {"form": form})
        # 获取数据 校验 并且更新数据
    form = PolicyModelForm(data=request.POST)  # 传入一个 instance = 数据库对象，没有instance就是新增
    if not form.is_valid():
        return render(request, 'form2.html', {"form": form})
    form.save()
    return redirect(reverse('policy_list'))





# 编辑价格策略
def policy_edit(request,pk):
    # 获取数据库的默认值
    instance = models.PricePolicy.objects.filter(id=pk).first()
    print("instance",instance)
    if request.method == "GET":
        form = PolicyModelForm(instance=instance)
        return render(request, "form2.html", {"form": form})
        # 获取数据 校验 并且更新数据
    form = PolicyModelForm(data=request.POST,instance=instance)  # 传入一个 instance = 数据库对象，没有instance就是新增
    if not form.is_valid():
        return render(request, 'form2.html', {"form": form})
    form.save()
    # 优化 ：修改数据后跳转回之前的界面
    url = filter_reverse(request, reverse('policy_list'))  # 函数方法实现
    return redirect(url)


# 删除价格策略
def policy_delete(request):
    cid = request.GET.get("cid")
    res = BaseResponse(status=True)
    models.PricePolicy.objects.filter(id=cid).delete()
    return JsonResponse(res.dict)
